import axios from 'axios'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import Ms from "@/utils/hooks" // 对应 element-plus 的 message、messageBox、notification

const config = {
  baseURL: "/api",
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  },
}

const requests = axios.create(config)
let autoTip = true



// 异常处理方法
function handerError(error) {
  nprogress.done()
  console.log('error ', error)
  //网络超时异常处理
  if (error.code === 'ECONNABORTED' || error.message === 'Network Error' || error.message.includes('timeout')) {
    let eMsg = ''
    try {
      eMsg = error.toString()
    } catch (e) {
      console.error(e)
      eMsg = e.message || e.statusText
    }
  }

  if (error.response) {
    let data = error.response.data;
    switch (error.response.status) {
      case 403: autoTip && Ms.notification('拒绝访问', '系统提示', { type: "error" }); break;
      case 500: autoTip && Ms.notification('访问接口失败', '系统提示', { type: "error" }); break;
      case 404: autoTip && Ms.notification('很抱歉，资源未找到!', '系统提示', { type: "error" }); break;
      case 504: autoTip && Ms.notification('网络超时', '系统提示', { type: "error" }); break;
      case 401: autoTip && Ms.notification('未授权，请重新登录', '系统提示', { type: "error" }); break;
      default: autoTip && Ms.notification(data.message, '系统提示', { type: "error" }); break;
    }
    return Promise.reject(data);
  } else {
    return Promise.reject(error);
  }
};



// 请求拦截器
requests.interceptors.request.use(function (config) {
  nprogress.start()
  config.headers['Access-Control-Allow-Origin'] = true
  config.headers['X-Access-Token'] = '1';
  config.headers['OrgId'] = '' // dd10517f7d3e405aa9097cfd618c6e6b
  config.headers['CurrentUserName'] = '' // administrator
  config.headers['EnterpriseId'] = '*'

  if (config.method == 'get') {
    config.params = {
      t: Date.parse(new Date()) / 1000,
      ...config.params,
    };
  }
  return config
}, error => {
  nprogress.done()
  return Promise.reject(error)
})

// 响应拦截器
requests.interceptors.response.use(function (response) {
  // console.log("响应拦截器-response: ", arguments)
  nprogress.done()
  const { data, status, statusText } = response
  if (status !== 200) {
    autoTip && Ms.notification(statusText, '提示', { type: "danger" })
    throw(response)
  } else if (data.success === false) { // 业务问题，自动提示
    autoTip && Ms.notification(data.message.content, '提示', { type: "error" })
    throw(data)
  } else {
    return data
  }
}, handerError)


// 暴露
export default {
  get(url, params, options={}) {
    autoTip = typeof options.autoTip === "boolean" ? options.autoTip : true
    return requests({ method: 'get', url, params })
  },
  post(url, params, options={}) {
    autoTip = typeof options.autoTip === "boolean" ? options.autoTip : true
    return requests({ method: 'post', url, data: params })
  },
}